package com.buka.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buka.domain.ResponseResult;
import com.buka.dto.TagListDto;
import com.buka.enums.AppHttpCodeEnum;
import com.buka.exception.SystemException;
import com.buka.mapper.TagMapper;
import com.buka.pojo.Tag;
import com.buka.service.TagService;
import com.buka.util.BeanCopyUtils;
import com.buka.vo.TagVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @description 针对表【tag(标签)】的数据库操作Service实现
 * @createDate 2024-05-24 10:05:59
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag>
        implements TagService {

    @Override
    public ResponseResult pageTagList(Integer pageNum, Integer pageSize, TagListDto tagListDto) {
        //分页查询
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.hasText(tagListDto.getName()), Tag::getName, tagListDto.getName());
        queryWrapper.eq(StringUtils.hasText(tagListDto.getRemark()), Tag::getRemark, tagListDto.getRemark());

        Page<Tag> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        page(page, queryWrapper);
        //封装数据返回
        Map<String, Object> map = new HashMap<>();
        map.put("rows", page.getRecords());
        map.put("total", page.getTotal());
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult add(Tag tag) {
        if (!StringUtils.hasText(tag.getName()) || !StringUtils.hasText(tag.getRemark())) {
            throw new SystemException(AppHttpCodeEnum.PARAMETER_ERROR);
        }
        getBaseMapper().insert(tag);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult delete(String id) {
        getBaseMapper().deleteById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult put(Tag tag) {
        if (!StringUtils.hasText(tag.getName()) || !StringUtils.hasText(tag.getRemark())) {
            throw new SystemException(AppHttpCodeEnum.PARAMETER_ERROR);
        }
        getBaseMapper().updateById(tag);
        return ResponseResult.okResult();
    }

    @Override
    public List<TagVo> listAllTag() {
        LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Tag::getId, Tag::getName);
        List<Tag> list = list(wrapper);
        List<TagVo> tagVos = BeanCopyUtils.copyBeanList(list, TagVo.class);
        return tagVos;
    }
}